<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */
// Include twitteroauth
include 'Libs/facebook/facebookauth.php';

class Facebook {

//put your code here
    public $facebook;
    public static $instance;
    public static $config = array(
        'appId' => '468798963236409',
        'secret' => '5c65cf7f877780c8d380241731e2d5da',
        'fileUpload' => false, // optional
        'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
    );

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }

    public function __construct() {
//allocate your stuff
    }

    public static function withData() {
        $instance = self::getInstance();
        $instance->facebook = new FacebookAuth(self::$config);
        return $instance;
    }

    public static function getUserId() {
        $instance = self::getInstance();
        $instance->facebook = new FacebookAuth(self::$config);
        $user_id = $instance->facebook->getUser();
        return $user_id;
    }

    public static function getAuthorization() {
        $instance = self::withData();
        $db = Database::getInstance();
        $id = $db->getID("facebooks", "id");
        $userId = User::getCurrentUserId();
        $accesstoken = $instance->facebook->getAccessToken();
        $facebookid = $instance->facebook->getUser();
        $me = $instance->facebook->api('/me');
        $screenname = $me['name'];
        $query = "INSERT INTO facebooks (id, userid, accesstoken, facebookid,
            username) VALUES ('$id', '$userId', '$accesstoken', '$facebookid', '$screenname')";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            return "true";
        } else {
            return "false";
        }
    }

    public static function getLoginURL() {
        $instance = self::withData();
        $url = $instance->facebook->getLoginUrl(array('scope' => 'publish_stream, user_status, user_friends, friends_status, read_stream, publish_actions'));
        return $url;
    }

    public static function getFacebookObjectId($userid, $postid) {
        $instance = self::withData();
        try {
            $response = $instance->facebook->api('/' . $userid . '_' . $postid . '/?access_token=CAAGqXsOsvjkBAEls784IgBInHTuANduNtZCsTDjn1lXZCLSpGZBIFev1OonNLNvRsYx0nfOWzlrSZBpKQAZAnDLb1XtpNOO2ejfZAXVkkZB3z9C10iLQOFvbKMQW7gbR6J06sfDrEuZCwlpREi4XQSI3kKq1GDSSRLkFZAn4c1i6AbnqBRPUa4v7z', 'GET');
        } catch (Exception $err) {
            return '';
        }
        return $response['object_id'];
    }

    public static function getFacebookUserid($postid, $commentid) {
        $instance = self::withData();
        try {
            $response = $instance->facebook->api('/' . $postid . '_' . $commentid . '?access_token=CAAGqXsOsvjkBAEls784IgBInHTuANduNtZCsTDjn1lXZCLSpGZBIFev1OonNLNvRsYx0nfOWzlrSZBpKQAZAnDLb1XtpNOO2ejfZAXVkkZB3z9C10iLQOFvbKMQW7gbR6J06sfDrEuZCwlpREi4XQSI3kKq1GDSSRLkFZAn4c1i6AbnqBRPUa4v7z', 'GET');
        } catch (Exception $err) {
            return '';
        }
        return $response['from']['id'];
    }

    public static function postFacebookStatus($messageId, $streamId, $message, $link) {
        if (User::getCurrentUserId()) {
            $signalId = Signal::getId($messageId);
            if ($signalId != 0)
                $saveSignal = Signal::withId($signalId);
            else
                $saveSignal = Signal::withData($messageId, $streamId);

            if ($saveSignal->shareCount)
                $saveSignal->shareCount++;
            else
                $saveSignal->shareCount = 1;
            $signalController = new SignalController($saveSignal, new SignalView());
            $signalController->save();
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT * FROM facebooks WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow == 1) {
                    $rows = $result->dataTable->rows[0];
                    $instance = self::withData();
                    try {
                        $response = $instance->facebook->api('/' . $rows['facebookid'] . '/feed?access_token=' . $rows['accesstoken'], 'post', array('message' => $message, 'link' => $link));
                    } catch (Exception $err) {
                        return $err->getMessage();
                    }
                    if ($response != 200) {
//Do something if the request was unsuccessful
                        return "There was an error posting the message.";
                    }
                    return "Posted";
                } else {
                    return "Not found data";
                }
            } else {
                return "Cannot connect database";
            }
        } else {
            return "No user log in";
        }
    }

    public static function getFacebooks() {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT * FROM facebooks WHERE userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    $username = '';
                    $userid = '';
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['name'];
                        $id = $row['facebookid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                    return array(
                        "screenname" => $username,
                        "accountid" => $userid
                    );
                } else {
                    return array(
                        "screenname" => 'undefined',
                        "accountid" => 'undefined'
                    );
                }
            } else {
                return array(
                    "screenname" => 'undefined',
                    "accountid" => 'undefined'
                );
            }
        } else {
            return array(
                "screenname" => 'undefined',
                "accountid" => 'undefined'
            );
        }
    }

    public static function deleteFacebook($facebookid) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $query = "DELETE FROM facebooks WHERE facebookid = '$facebookid'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            } else {
                return "false";
            }
        } else {
            return "false";
        }
    }

    public static function comment($fbPostID, $message) {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT facebooks.userid, facebooks.accesstoken FROM facebooks WHERE facebooks.userid = '$userId'";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    $instance = self::withData();
                    foreach ($result->dataTable->rows as $row) {
//echo $row['accesstoken'];
                        try {
                            $instance->facebook->api('/' . $fbPostID . '/comments?access_token=' . $row['accesstoken'], 'POST', array('message' => $message));
                        } catch (Exception $err) {
                            
                        }
                    }
                    return "Posted";
                } else {
                    return "You are not connected to facebook";
                }
            } else {
                return "Cannot connect database";
            }
        } else {
            return "No user log in";
        }
    }

}

?>